package com.movisol.questionwizard.applicationcontroller.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;

import com.movisol.questionwizard.applicationcontroller.events.PushNotificationSubscribedEvent;
import com.movisol.questionwizard.applicationcontroller.listeners.IPushNotificationSubscribed;
import com.movisol.tools.HelperUtils;

public class ProfileServiceManager {//implements IProfileServiceManager {
	
	private Context context;
//	private String error;
//	protected List<IUserProfileDataLoadedListener> userProfileDataLoadedListeners = new ArrayList<IUserProfileDataLoadedListener>();
//	protected List<IFriendsDataLoadedListener> friendsDataLoadedListeners = new ArrayList<IFriendsDataLoadedListener>();
//	protected List<IFriendsDataLoadedListener> friendsDataUpdatedListeners = new ArrayList<IFriendsDataLoadedListener>();
	protected List<IPushNotificationSubscribed> pushNotificationSubscribed = new ArrayList<IPushNotificationSubscribed>();
	
	
	public ProfileServiceManager(Context context){
		
		this.context = context;
	}
	
	
//	/******************UserProfileDataLoaded*****************/
//	public synchronized void addUserProfileDataLoadedListener(IUserProfileDataLoadedListener listener){
//		
//		if(!userProfileDataLoadedListeners.contains(listener))
//			userProfileDataLoadedListeners.add(listener);
//	}
//	
//	
//	public synchronized void removeUserProfileDataLoadedListener(IUserProfileDataLoadedListener listener){
//		
//		userProfileDataLoadedListeners.remove(listener);
//	}
//	
//	
//	/**
//	 * Fires all the Events for all the listener subscribed
//	 */
//	public void fireUserProfileDataLoadedEvent(String error){
//		
//		DataLoadedEvent dle = null;
//		dle = new DataLoadedEvent(this, error);
//		Iterator<IUserProfileDataLoadedListener> it = userProfileDataLoadedListeners.listIterator();
//		while (it.hasNext()){
//			 it.next().userProfileDataLoaded(dle);
//		}
//	}
//	/********************************************************/
//	
//	
//	
//	/********************FriendsDataLoaded******************/
//	public synchronized void addFriendsDataLoadedListener(IFriendsDataLoadedListener listener){
//		
//		if(!friendsDataLoadedListeners.contains(listener))
//			friendsDataLoadedListeners.add(listener);
//	}
//	
//	
//	public synchronized void removeFriendsDataLoadedListener(IFriendsDataLoadedListener listener){
//		
//			friendsDataLoadedListeners.remove(listener);
//	}
//	
//	
//	/**
//	 * Fires all the Events for all the listener subscribed
//	 */
//	public void fireFriendsDataLoadedEvent(String error){
//		
//		DataLoadedEvent dle = null;
//		dle = new DataLoadedEvent(this, error);
//		Iterator<IFriendsDataLoadedListener> it = friendsDataLoadedListeners.listIterator();
//		while (it.hasNext()){
//			 it.next().friendsDataLoaded(dle);
//		}
//	}
//	/********************************************************/
//	
//	
//		
//	/********************FriendsDataUpdated*****************/
//	public synchronized void addFriendsDataUpdatedListener(IFriendsDataLoadedListener listener){
//		
//		if(!friendsDataUpdatedListeners.contains(listener))
//			friendsDataUpdatedListeners.add(listener);
//	}
//	
//	
//	public synchronized void removeFriendsDataUpdatedListener(IFriendsDataLoadedListener listener){
//		
//		friendsDataUpdatedListeners.remove(listener);
//	}
//	
//	
//	/**
//	 * Fires all the Events for all the listener subscribed
//	 */
//	public void fireFriendsDataUpdatedEvent(String error){
//		
//		DataLoadedEvent dle = null;
//		dle = new DataLoadedEvent(this, error);
//		Iterator<IFriendsDataLoadedListener> it = friendsDataUpdatedListeners.listIterator();
//		while (it.hasNext()){
//			 it.next().friendsDataLoaded(dle);
//		}
//	}
//	/********************************************************/
//	
	/********************PushNotificationSubscribed*****************/
	public synchronized void addPushNotificationSubscribedListener(IPushNotificationSubscribed listener){
		
		if(!pushNotificationSubscribed.contains(listener))
			pushNotificationSubscribed.add(listener);
	}
	
	
	public synchronized void removePushNotificationSubscribedListener(IPushNotificationSubscribed listener){
		
		pushNotificationSubscribed.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void firePushNotificationSubscribedEvent(String error){
		
		PushNotificationSubscribedEvent pnse = null;
		pnse = new PushNotificationSubscribedEvent(this, error);
		Iterator<IPushNotificationSubscribed> it = pushNotificationSubscribed.listIterator();
		while (it.hasNext()){
			 it.next().pushNotificationSubscribed(pnse);
		}
	}
	/********************************************************/
	
	


	
//	@Override
//	public String saveUserProfile(UserProfile profileData) {
//		
//		
//		HttpClient client = new DefaultHttpClient();
//		String result = null;
//		BufferedReader in = null;
//		
//		try {
//			HttpPut request = new HttpPut(HelperUtils.getConfigParam("FQDN", context) + "/ProfileService.svc/UserProfile/"+ HelperUtils.getDeviceId(context) +"/");
//			String sXML = MessengerProfileHelper.parseUserProfileToXML(profileData);
//			StringEntity se = new StringEntity(sXML,"UTF-8");
//			Log.d("MessengerManager","XML file to Send:"+sXML);
//			se.setContentType("application/atom+xml"); 
//			request.setEntity(se);
//			HttpResponse response = client.execute(request);
//			
//			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8192);
//			StringBuffer sb = new StringBuffer("");
//			String line = "";
//			String NL = System.getProperty("line.separator");
//				while ((line = in.readLine()) != null) {
//				sb.append(line + NL);
//				}
////			in.close();
//			result = sb.toString();
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			} catch (ClientProtocolException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}finally{
//				if(in != null)
//					try {
//						if(in != null)
//							in.close();
//					} catch (IOException e) {
//
//						System.out.println("Problema al cerrar el objeto lector");
//					}
//		}
//		//TODO controlar en caso de que sea null para mostrar mensaje de error (NO CONEXION)
//		return result;
//	}
//
//	
//	@Override
//	public String getUserFriends(String sku, String version, String languageId, String userId, String signature) {
//			
//		URL url;
//		String result = null;
//		BufferedReader br = null;
//		try {
//			url = new URL(HelperUtils.getConfigParam("FQDN", context)+ "/ProfileService.svc/Friends/"+ sku + "/"  + version + "/" + languageId + "/" + userId + "/" + signature + "/");
//			URLConnection c =  url.openConnection();
//			c.setDoOutput(true);
//			c.connect();
//			InputStreamReader ins = new InputStreamReader(c.getInputStream());
//
//			
//			br = new BufferedReader(ins, 8192);
//			StringBuffer sb = new StringBuffer();
//
//			//Guardamos el stream recibido			
//			String len1;
//			while ((len1 = br.readLine()) != null) {
//				sb.append(len1);
//			}
//			result = sb.toString();
//
//			} catch (MalformedURLException e) {
//
//				e.printStackTrace();
//			} catch (ProtocolException e) {
//
//				e.printStackTrace();
//			} catch (IOException e) {
//
//				e.printStackTrace();
//			}finally {
//	            if (br != null) {
//	                try {
//	                	br.close();
//	                } catch (IOException ex) {
//	                    System.out.println("Problema al cerrar el objeto lector");
//	                }
//	            }
//		}
//
//		return result;
//	}
//
//	
//	@Override
//	public String updateUserFriends(String sku, String version, String languageId, String userId, Friends friends) {
//		
//		HttpClient client = new DefaultHttpClient();
//		String result = null;
//		BufferedReader in = null;
//		
//		try {
//			HttpPut request = new HttpPut(HelperUtils.getConfigParam("FQDN", context) + "/ProfileService.svc/Friends/"+ sku + "/"  + version + "/" + languageId + "/" + userId + "/");
//			
//			String sXML = MessengerProfileHelper.parseFriendsToXML(friends);
//			
//			StringEntity se = new StringEntity(sXML,"UTF-8");
//			Log.d("MessengerManager","XML file to Send:"+sXML);
//			se.setContentType("application/atom+xml"); 
//			request.setEntity(se);
//			HttpResponse response = client.execute(request);
//			
//			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8192);
//			StringBuffer sb = new StringBuffer("");
//			String line = "";
//			String NL = System.getProperty("line.separator");
//				while ((line = in.readLine()) != null) {
//				sb.append(line + NL);
//				}
//			in.close();
//			result = sb.toString();
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			} catch (ClientProtocolException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}finally{
//				if(in != null)
//					try {
//						in.close();
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						System.out.println("Problema al cerrar el objeto lector");
//					}
//		}
//		//TODO controlar en caso de que sea null para mostrar mensaje de error (NO CONEXION)
//		return result;
//
//	}
//
//	
//	@Override
//	public String updateUserNotificacion(String sku, String version, String medium, String mediumId) {
//		// TODO Auto-generated method stub
//		return "";
//	}
	
	public String subscribeNotificationPush(String sku, String version, String languageId, String uuid, String medium, String mediumId)
	{
		HttpClient client = new DefaultHttpClient();
		String result = null;
		BufferedReader in = null;
		
		try {

			HttpPut request = new HttpPut(HelperUtils.getConfigParam("FQDN", context)+ "/ProfileService.svc/UserProfile/Notification/"+sku+"/"+version+"/"+languageId+"/"+uuid+"/"+medium+"/?mediumId="+mediumId);
			HttpResponse response = client.execute(request);
			
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8192);
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
				sb.append(line + NL);
				}
			in.close();
			result = sb.toString();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(in != null)
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						System.out.println("Problema al cerrar el objeto lector");
					}
		}
		//TODO controlar en caso de que sea null para mostrar mensaje de error (NO CONEXION)
		return result;
	}
	
	

}
